package internal

import (
	"encoding/json"
	"fmt"
	"gitee.com/game_35/libs/color"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
	db1 "server/libs/db"
	"time"
)

type AtService struct {
}

type Order struct {
	Id             int64     `json:"id"`
	UserId         int64     `json:"user_id"`
	Code           string    `json:"code"`
	Amount         float64   `json:"amount"`                                         // 金额
	TrackNum       int32     `gorm:"column:track_num; json:"track_num"`              // 赛道号码
	BetNum         int32     `gorm:"column:bet_num;json:"bet_num"`                   // 投注号码
	SingleEvenDict int32     `gorm:"column:single_even_dict;json:"single_even_dict"` // 号码单双
	BigSmallDict   int32     `gorm:"column:big_small_dict;json:"big_small_dict"`     // 号码大小
	AwardNum       float64   `json:"award_num"`
	CreatedAt      time.Time `json:"created_at"` // 创建时间
}

func (this AtService) IssueCalculatorWinPrizeAmount(issue int64) {

	var awardRecord struct {
		Id           int64  `json:"Id"`
		OpenIssueNum int64  `json:"open_issue_num"`
		AwardNum     string `json:"award_num"`
	}

	db1.Mysql().Table("home_award_record").Where("open_issue_num=?", issue).First(&awardRecord)
	//  获取开奖 number
	openNumbers := []int64{}
	json.Unmarshal([]byte(awardRecord.AwardNum), &openNumbers)

	openResult := NewGenerate().GetAwardData(openNumbers)

	//  计算用户奖励
	var orders []Order
	db1.Mysql().Debug().Table("home_order").Where("issue_num=? and order_state_dict=1", issue).Scan(&orders)
	for k := range orders {
		// 计算奖励
		BetDetail := RestoreBetDetail(orders[k].TrackNum, orders[k].BetNum, orders[k].BigSmallDict, orders[k].SingleEvenDict)
		a := decimal.NewFromFloat(openResult[BetDetail])
		c := decimal.NewFromFloat(orders[k].Amount)
		d := decimal.NewFromFloat(orders[k].Amount)
		orders[k].AwardNum, _ = a.Mul(c).Sub(d).RoundFloor(2).Float64()

		color.Redln("c&update AwardNum ; issue/id/AwardNum      ", issue, "/ ", orders[k].Id, "/ ", orders[k].AwardNum, fmt.Sprintf("    %d/%d", k+1, len(orders)))
		db1.Mysql().Debug().Table("home_order").Where("id=?", orders[k].Id).Updates(map[string]any{
			"award_num": orders[k].AwardNum,
		})
	}
}

func (this AtService) ThisIssueAllOrderTransfer(issue int64) {
	var orders []Order
	db1.Mysql().Debug().Table("home_order").Where("issue_num=? and order_state_dict=1", issue).Scan(&orders)
	for k := range orders {
		color.Yellowln("Transfer order id:", orders[k].Id)
		err := this.Transfer(orders[k].Id)
		if err != nil {
			color.Redln("issue transfer failed, errmgs: ", err)
		}
	}
}

func (this AtService) Transfer(id int64) error {
	return db1.Mysql().Transaction(func(tx *gorm.DB) error {
		var order struct {
			Id       int64   `json:"id"`
			AwardNum float64 `json:"award_num"`
			UserId   int64   `json:"user_id"`
		}

		tx.Model("home_order").Where("id=?", id).Select("id,user_id,award_num").Scan(&order)

		err := tx.Model("home_order").Where("id=?", id).Updates(map[string]any{
			"order_state_dict": BET_PROGRESS,
			"updated_at":       time.Now().Format("2006-01-02 15:04:05"),
		}).Error
		if err != nil {
			return err
		}

		if order.AwardNum <= 0 {
			return nil
		}

		return new(AccountService).TransferTx(tx, order.UserId, order.AwardNum, WIN_LOSE, order.Id, "win prize")
	})
}
